﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using University.Workshop.Business;
using University.Workshop.WinApp.Clients;
using University.Workshop.WinApp.Product;
using University.Workshop.Model;
using University.Workshop.Presenters;
using System.Collections.ObjectModel;

namespace University.Workshop.WinApp.Sale
{
    public partial class SaleRegister : UserControl,ISale
    {
        private RegistrationSalePresenter salePresenter;
        UserLogOn user = UserLogOn.Instance;
        SaleVariables variable = SaleVariables.Instance;
        Variables flag = Variables.Instance;

        static int indexData;
        public SaleRegister()
        {
            InitializeComponent();
            indexData = 0;
            variable.IndexProductsReply = 0;
            variable.ResetReplyProducts();
            salePresenter = new RegistrationSalePresenter(this);
            textBoxUserName.Text = user.Name + " " + user.Surname1 + " " + user.Surname2;
            GetSaleCode();
        }

        private void GetSaleCode()
        {
            textBoxSaleCode.Text = SaleController.GetSaleCode();
        }

        #region SendParameter
        public string ClientCode{ get { return textBoxClientCode.Text; } }
        public string SaleCode{ get { return textBoxSaleCode.Text; } }
        public string UserCode{ get { return user.Id; } }
        public DateTime DateSale{ get { return dateTimePickerDateSale.Value; } }
        public string TotalAmount { get { return labelTotalAmount.Text; } }
        public string Message { get { return ""; } set { MessageBox.Show(value); } }
        public Collection<SaleDetail> ListOfProducts { get { return ReturnAllSelectProducts(); } }
        public string CodeProduct { get { return textBoxProductCode.Text; } }
        public string Quantity { get { return textBoxProductQuantity.Text; } }
        public string StockQuantity { get { return textBoxStockQuantity.Text; } }
        public string UnitPrice { get { return textBoxProductPrice.Text; } }
        private Collection<SaleDetail> ReturnAllSelectProducts()
        {
            Collection<SaleDetail> list = new Collection<SaleDetail>();
            for (int i = 0; i < dataGridViewProducts.Rows.Count;i++ )
            {
                SaleDetail saleProduct = new SaleDetail();
                saleProduct.CodeSale = textBoxSaleCode.Text;
                saleProduct.CodeProduct = dataGridViewProducts.Rows[i].Cells[0].Value.ToString();
                saleProduct.UnitPrice = Convert.ToDouble(dataGridViewProducts.Rows[i].Cells[1].Value.ToString(), System.Globalization.CultureInfo.CurrentCulture);
                saleProduct.Quantity = Convert.ToInt32(dataGridViewProducts.Rows[i].Cells[2].Value.ToString(), System.Globalization.CultureInfo.CurrentCulture);
                saleProduct.TotalPrice = Convert.ToDouble(dataGridViewProducts.Rows[i].Cells[3].Value.ToString(), System.Globalization.CultureInfo.CurrentCulture);
                list.Add(saleProduct);
            }
            return list;
        }
        #endregion

        private void buttonClientBrowser_Click(object sender, EventArgs e)
        {
            flag.Client = "BrowserClientSale";
            FormClientsView clientView = new FormClientsView();
            clientView.ShowDialog();
            textBoxClientCode.Text = variable.IdClient;
            textBoxClientName.Text = variable.FullNameClient;
        }

        private void buttonProductBrowser_Click(object sender, EventArgs e)
        {
            flag.Product = "BrowserProductSale";
            FormProductView productView = new FormProductView();
            productView.ShowDialog();
            if (!string.IsNullOrEmpty(variable.ProductCode))
            {
                textBoxProductCode.Text = variable.ProductCode;
                DataTable table = SaleController.GetProductRow(variable.ProductCode);
                if(table.Rows.Count!=0)
                {
                    textBoxProductName.Text = table.Rows[0].ItemArray[0].ToString();
                    textBoxProductType.Text = table.Rows[0].ItemArray[1].ToString();
                    textBoxStockQuantity.Text = table.Rows[0].ItemArray[2].ToString();
                    textBoxProductPrice.Text = table.Rows[0].ItemArray[3].ToString();
                }
            }
        }

        private void buttonSaleRegister_Click(object sender, EventArgs e)
        {
            string resp =salePresenter.OnSaleRegistration();
            string gifts;
            if (resp == "Registro de venta exitosa")
            {
                gifts=GiftsControl.GetGiftByPricesAndClient(textBoxClientCode.Text,labelTotalAmount.Text);
                MessageBox.Show(this, resp, "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
               if(gifts!=string.Empty){
                MessageBox.Show(this, gifts, "PREMIOS!!!!", MessageBoxButtons.OK,
        MessageBoxIcon.Information, MessageBoxDefaultButton.Button1,
        MessageBoxOptions.RightAlign);
                FormSaleView.Intance.GoToMainView();
               }
            }
            else
                MessageBox.Show(this, resp, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
        }

        private void buttonAddToList_Click(object sender, EventArgs e)
        {
            string resp=salePresenter.OnAddProductToList();
            if (!IfProductExistsOnList(textBoxProductCode.Text))
            {
                if (resp == "Todo esta bien")
                {
                    dataGridViewProducts.Rows.Add();
                    dataGridViewProducts.Rows[indexData].Cells[0].Value = textBoxProductCode.Text;
                    dataGridViewProducts.Rows[indexData].Cells[1].Value = textBoxProductPrice.Text;
                    dataGridViewProducts.Rows[indexData].Cells[2].Value = textBoxProductQuantity.Text;
                    dataGridViewProducts.Rows[indexData].Cells[3].Value = (Convert.ToDouble(textBoxProductQuantity.Text) * Convert.ToDouble(textBoxProductPrice.Text)).ToString();
                    indexData++;
                    labelTotalAmount.Text = (Convert.ToDouble(labelTotalAmount.Text) + (Convert.ToDouble(textBoxProductQuantity.Text) * Convert.ToDouble(textBoxProductPrice.Text))).ToString();
                    ClearProductsFills();
                    variable.ReplyProducts[variable.IndexProductsReply] = variable.ProductCode;
                    variable.IndexProductsReply++;
                }
                else
                    MessageBox.Show(this, resp, "Error al añadir producto", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
            }
            else
                MessageBox.Show(this, "Ya existe el producto en la lista de venta!", "Repetido", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
        }

        private bool IfProductExistsOnList(string code)
        {
            bool resp = true;
            for (int i = 0; i < variable.IndexProductsReply; i++)
            {
                if (variable.ReplyProducts[i] == code)
                    return resp;
            }
            return resp = false;
        }

        private void ClearProductsFills()
        {
            textBoxProductCode.Clear();
            textBoxProductName.Clear();
            textBoxProductType.Clear();
            textBoxProductQuantity.Clear();
            textBoxProductPrice.Clear();
            textBoxStockQuantity.Clear();
        }

        private void buttonSaleCancel_Click(object sender, EventArgs e)
        {
            FormSaleView.Intance.GoToMainView();        
        }

        private void buttonDeleteProduct_Click(object sender, EventArgs e)
        {
            if(dataGridViewProducts.Rows.Count!=0)
            {
                dataGridViewProducts.SelectedRows[0].Visible = false;
                labelTotalAmount.Text = (Convert.ToDouble(labelTotalAmount.Text) - (Convert.ToDouble(dataGridViewProducts.SelectedRows[0].Cells[3].Value.ToString()))).ToString();
                for (int i = 0; i < variable.IndexProductsReply; i++)
                {
                    if (variable.ReplyProducts[i] == dataGridViewProducts.SelectedRows[0].Cells[0].Value.ToString())
                        variable.ReplyProducts[i] = "Nothing";
                }
                indexData--;
                dataGridViewProducts.Rows.RemoveAt(dataGridViewProducts.SelectedRows[0].Index);
            }
        }

        private void buttonViewSugerency_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxCaracteristic.Text))
            {
                MessageBox.Show("Campo de caracteristicas vacio!!!");
            }
            else
            {
                DataTable dtb = new DataTable();
                ProductSuggestionView suggestion = new ProductSuggestionView(textBoxCaracteristic.Text);
                suggestion.ShowDialog();
                textBoxProductCode.Text = Model.Product.Instance.CodeProduct;
                textBoxProductName.Text = Model.Product.Instance.NameProduct;
                textBoxProductType.Text = Model.Product.Instance.Presentation;
                dtb = ProductController.QuantityAndPriceSale(textBoxProductCode.Text);
                textBoxStockQuantity.Text = dtb.Rows[0].ItemArray[0].ToString();
                textBoxProductPrice.Text = dtb.Rows[0].ItemArray[1].ToString();
            }
        }

        private void Validator_only_Characters_KeyPress(object sender, KeyPressEventArgs e)
        {
            Validator.ValidatorOnlyCharacters(sender, e);
        }

        private void Validator_Only_Numbers_KeyPress(object sender, KeyPressEventArgs e)
        {
            Validator.ValidatorOnlyNumbers(sender, e);
        }

        private void MessageSuggestion(object sender, MouseEventArgs e)
        {
            MessageBox.Show("Sugerencia en el campo de busqueda: cabeza,resfrio,espalda,mareos,ojos");
        }
    }
}
